import Cookies from 'js-cookie'

export const TOKEN_KEY = 'PZ_TOKEN'

export const setToken = (token) => {
  localStorage.setItem(TOKEN_KEY, token)
  if (token === '' || token === undefined) {
    clearToken()
  }
}

export const clearToken = () => {
  localStorage.removeItem(TOKEN_KEY)
}

export const getToken = () => {
  const token = localStorage.getItem(TOKEN_KEY)
  if (token) return token
  else return false
}
export const clearCookies = () => {
  Cookies.remove(TOKEN_KEY)
}
/**
 * @param {Array} routeMetched 当前路由metched
 * @returns {Array}
 */
export const getBreadCrumbList = (route, homeRoute) => {
  console.log(route, homeRoute, '执行函数')
  let homeItem = { ...homeRoute, icon: homeRoute.meta.icon }
  let routeMetched = route.matched
  if (routeMetched.some(item => item.name === homeRoute.name)) return [homeItem]
  let res = routeMetched.filter(item => {
    return item.meta === undefined || !item.meta.hideInBread
  }).map(item => {
    let meta = { ...item.meta }
    if (meta.title && typeof meta.title === 'function') {
      meta.__titleIsFunction__ = true
      meta.title = meta.title(route)
    }
    let obj = {
      icon: (item.meta && item.meta.icon) || '',
      name: item.name,
      meta: meta
    }
    return obj
  })
  res = res.filter(item => {
    return !item.meta.hideInMenu
  })
  return [{ ...homeItem, to: homeRoute.path }, ...res]
}
/**
 * @param {Array} routers 路由列表数组
 * @description 用于找到路由列表中name为home的对象
 */
export const getHomeRoute = (routers, homeName = 'home') => {
  let i = -1
  let len = routers.length
  let homeRoute = {}
  while (++i < len) {
    let item = routers[i]
    if (item.children && item.children.length) {
      let res = getHomeRoute(item.children, homeName)
      if (res.name) return res
    } else {
      if (item.name === homeName) homeRoute = item
    }
  }
  return homeRoute
}

export const showTitle = (item, vm) => {
  let { title } = item.meta
  if (!title) return
  title = (item.meta && item.meta.title) || item.name
  return title
}

export const phpMenusfilter = (data) => {
  return data
}
export const javaMenusfilter = (data) => {
  return data
}
export const isIos = () => {
  let equipmentType = ''
  let agent = navigator.userAgent.toLowerCase()
  let android = agent.indexOf('android')
  let iphone = agent.indexOf('iphone')
  let ipad = agent.indexOf('ipad')
  if (android !== -1) {
    equipmentType = false
  }
  if (iphone !== -1 || ipad !== -1) {
    equipmentType = true
  }
  return equipmentType
}

export const isEmpty = (data) => {
  if (data === '' || data === null || data === undefined || data === 'undefined') {
    return true
  } else {
    return false
  }
}

export const saveCookie = (key, data) => {
  Cookies.set(key, data, { expires: 1 })
}

export const getCookie = (key) => {
  const token = Cookies.get(key)
  if (token) return token
  else return false
}
